package com.genzou.convert

class Convertor<T>{
    List<Closure> convertors = []
    List<Closure> filters = []
    Closure backuper = { it }
    
    final List<T> backupObjects = []
    final List<T> convertedObjects = []
    
    void setConvertors( List convertors ){
        this.convertors = convertors?:[]
    }
    
    void setFilters( List filters ){
        this.filters = filters?:[]
    }
    
    void setBackup( Closure c ){
        this.backuper = c?:{ it }
    }
    
    void clear(){
        this.convertors.clear()
        this.filters.clear()
        this.backuper = { it }
        this.backupObjects.clear()
        this.convertedObjects.clear()
    }
    
    List<T> convert(List<T> objects){
        
        if( !objects ){
            objects = []
        }
        
        this.backupObjects.clear()
        this.convertedObjects.clear()
        
        if( !this.convertors.size() ){
            return objects
        }
        
        objects.collect{ T obj ->
            if( filters.find{ !it.call(obj) } ){
                obj
            } else {
                this.backupObjects << this.backuper(obj)
                
                T newobj = obj
                this.convertors.each{
                    newobj = it(newobj)
                }
                this.convertedObjects << newobj
                
                newobj
            }
        }
    }
}